<template>
  <div class="userOrg">
    <Row style="margin-bottom: 6px;">
      <Col span="24" class="selectOrg">
        <AutoComplete
          v-model="nameOrCode"
          @on-search="remoteSearch"
          @on-select="selsectOrg"
          @on-clear="clearSearch"
          :placeholder="$t('module.treeManage.warning.enterNodeNameCode')"
          style="margin: auto; display: block;"
          icon="md-search"
          clearable
        >
          <Spin size="large" v-if="spinShow">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <span>加载中...</span>
          </Spin>
          <p v-if="!spinShow && nameOrCode.length && !searchResult.length && !loading" style="text-align: center;">
            暂无数据
          </p>
          <Option v-for="(option, index) in searchResult" :value="option" :key="index">{{ option }}</Option>
          <p
            class="complete-more get-complete-more"
            v-if="searchResult.length >= 10 && isShowMore"
            @click="showMore"
          >{{ $t("common.showMore") }}</p>
        </AutoComplete>
      </Col>
    </Row>
    <!-- <Spin v-if="isShowSpin">{{ searchHint }}</Spin> -->
    <div>
      <el-tree
        style="margin-top: 0; padding: 0; width: 100%;"
        ref="orgTree"
        lazy
        :data="baseData"
        :props="defaultProps"
        node-key="orgId"
        :default-expanded-keys="expandedKeys"
        :load="loadData"
        :render-content="renderContent"
        :expand-on-click-node="false"
        class="tree-box"
        icon-class="ivu-icon-ios-arrow-forward"
        highlight-current
        check-strictly
        :indent="16"
        @node-click="onNodeClick"
      ></el-tree>
    </div>
  </div>
</template>

<script>
import publicApi from "@/api/public.js";

export default {
  name: "nameOrganization",
  props: {
    query: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      fun: null,
      isLazy: true,
      isShowSpin: false,
      searchHint: "",
      defaultProps: {
        children: "childrenDept",
        label: "orgName"
      },
      isShowMore: false,
      expandedKeys: [],
      list: [],
      nameOrCode: "",
      searchResult: [],
      loading: false,
      orgList: [],
      baseData: [],
      embedSvg: orgType => {
        let svgUrl;
        switch (+orgType) {
          case 1:
            svgUrl = "static\\images\\enterprise.svg";
            break;
          case 2:
            svgUrl = "static\\images\\company.svg";
            break;
          case 10:
            svgUrl = "static\\images\\department.svg";
            break;
          default:
            svgUrl = "";
        }
        return svgUrl;
      },
      spinShow: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 搜索结果大于10条，点击查看更多
    showMore() {
      this.getSelectNode(this.nameOrCode);
    },
    getSelectNode(value) {
      // 点击查看更多，pageNum改为2，从第二页开始查询
      this.pageNum++;
      if (value && value.indexOf("/") == -1) {
        let param = {
          condition: {
            nameOrCode: value,
            orgTypeFilter: 3,
            enabled: 1
          },
          pageNum: this.pageNum,
          pageSize: 10
        };
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            if (data.records.length > 0) {
              this.loading = false;
              let pathArr = [];
              let orgArr = [];
              const list = data.records.map(item => {
                pathArr.push(item.orgNameFullPath);
              });

              orgArr = data.records;

              this.$nextTick(() => {
                this.searchResult = this.searchResult.concat(pathArr);
                this.orgList = this.orgList.concat(orgArr);
              });
              if (data.pages == this.pageNum) this.isShowMore = false;
            } else {
              // 查询结果，data.records为空数组时，隐藏查看更多按钮
              this.isShowMore = false;
            }
          })
          .catch(err => {
            this.loading = false;
          });
      }
    },
    selsectOrg(value) {
      this.expandedKeys = [];
      this.$refs.orgTree.store.lazy = false;
      let data = this.orgList.filter(item => {
        if (item.orgNameFullPath == value) {
          this.expandedKeys.push(item.orgId);
          return item.orgId;
        }
      });
      this.$emit("selsectOrg", data[0]);
      publicApi
        .getTreeBySelectOrg({ orgId: data[0].orgId, orgTypeFilter: 1 })
        .then(data => {
          this.baseData = data;
          this.$nextTick(() => {
            this.$refs["orgTree"].setCurrentKey(this.expandedKeys[0]);
            this.$refs.orgTree.store.lazy = true;
          });
        })
        .catch(err => {
          this.loading = false;
        });
    },
    renderContent(h, { node, data, store }) {
      return (
        <span>
          <span>
            <embed src={this.embedSvg(data.orgType)} width="10" height="10" type="image/svg+xml" class="node-svg" />
            <span class="node-label">{node.label}</span>
          </span>
        </span>
      );
    },
    loadData(node, resolve) {
      if (node.level == 0) {
        // 隐藏根节点
        return;
      }
      // 是叶子节点不进行查询
      if (node.isLeaf) {
        resolve([]);
      }
      publicApi.queryOrg({ orgPath: node.data.orgPath, orgTypeFilter: 3, enabled: 1 }).then(children => {
        resolve(children);
      });
    },
    debounce(fn, wait = 300) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    // 根据组织树编码和名称搜索
    remoteSearch() {
      this.debounce(() => {
        this.getListOrganizationPaths(this.nameOrCode);
      }, 300);
    },
    getListOrganizationPaths(value) {
      this.pageNum = 1; // 当重新搜索时，默认从第一页开始查询
      this.isShowMore = true; // 当重新搜索时，默认显示查看更多
      // this.searchResult = []; //数组中只包含orgNameFullPath
      this.orgList = []; // 数组中包含orgId orgNameFullPath orgName orgPath
      let param = {
        condition: {
          nameOrCode: value,
          orgTypeFilter: 3,
          enabled: 1
        },
        pageNum: 1,
        pageSize: 10
      };
      if (value !== "") {
        this.loading = true;
        this.spinShow = true;
        publicApi
          .getListOrganizationPaths(param)
          .then(data => {
            this.searchResult = [];
            this.loading = false;
            const list = data.records.map(item => {
              this.searchResult.push(item.orgNameFullPath);
            });
            this.orgList = data.records;
            if(data.pages == this.pageNum)this.isShowMore = false;
          })
          .catch(err => {
            this.loading = false;
          })
          .finally(() => {
            this.spinShow = false;
          })
      } else {
        this.orgList = [];
        this.spinShow = false;
      }
    },
    // 点击清空按钮
    clearSearch() {
      this.searchResult = [];
      this.nameOrCode = "";
      this.expandedKeys = [];
      this.$refs.orgTree.store.lazy = true;
      this.init();
    },
    // 初始化的时候，获取组织树的根节点
    init() {
      publicApi.queryOrg(this.query).then(data => {
        this.baseData = data;
        this.$emit("handleOnNodeClick", data[0]);
        this.$nextTick(function() {
          this.selectFirstOrg();
        });
      });
    },
    // 当前行加选中效果
    selectFirstOrg() {
      if (this.baseData.length > 0) {
        this.$refs["orgTree"].setCurrentKey(this.baseData[0].orgId);
      }
    },
    // 点击组织树节点
    onNodeClick(data) {
      this.$emit("handleOnNodeClick", data);
    }
  },
  watch: {
    nameOrCode: {
      handler(value) {
        if (!value) {
          this.clearSearch();
        }
      },
      deep: true
    }
  }
};
</script>

<style lang="less">
.userOrg {
  .node-label {
    margin-left: 3px;
  }
  .selectOrg {
    .ivu-select-dropdown {
      max-width: 674px !important;
      max-height: 330px !important;
      left: 0;
      .ivu-select-dropdown-list {
        width: fit-content;
        .ivu-select-item:hover {
          background: #fff !important;
        }
      }
    }
    display: flex;
    justify-content: center;
    padding: 0;
  }
  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
  }
}
</style>
